﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using CustomControl;
using TeacherLeftHand.View;

namespace TeacherLeftHand.Util
{

    public class XMLUtilitizer
    {
        #region constants

        public const string KIpath = "KIpath";
        public const string TMpath = "TMpath";
        #endregion

        /// <summary>
        /// load xml document from a file
        /// </summary>
        /// <param name="dbName">key name of the database in app.config</param>
        /// <returns></returns>
        public static XElement Load(string dbName)
        {
            var path = GetFilePath(dbName);
            if (File.Exists(path))
            {
                return XElement.Load(path);
            }
            else
            {
                throw new FileNotFoundException();
            }

        }

        public static string GetFilePath(string key)
        {
            return ConfigurationManager.AppSettings.Get(key);
        }
        //public static string ConvertXamlToString(FlowDocument fd)
        //{
        //    //string format = "@TAG@{0}:{1}@TAG@";
        //    string xamlString = "";
        //    var flowDocument = new FlowDocument();

        //    for (int i = 0; i < fd.Blocks.Count; i++)
        //    {
        //        var block = (fd.Blocks as BlockCollection).ElementAt(i);
        //        if (block is Paragraph)
        //        {
        //            var p = new Paragraph();
        //            for (int y = 0; y < ((Paragraph)block).Inlines.Count; y++)
        //            {

        //                var inline = ((Paragraph)block).Inlines.ElementAt(y);

        //                if (inline is InlineUIContainer)
        //                {
        //                    var elem = ((InlineUIContainer)inline).Child;
        //                    //if (elem is FlashControl)
        //                    //{
        //                    //    TextBox mc = new TextBox() { Text = string.Format(format, "FlashControl", (elem as FlashControl).Flashp.Source) };
        //                    //    p.Inlines.Add(mc);
        //                    //}
        //                    //else if (elem is MusicControl)
        //                    //{
        //                    //    MusicControl mc = new MusicControl((elem as MusicControl).Path_file);
        //                    //    p.Inlines.Add(mc);
        //                    //}
        //                    //else 
        //                    if (elem is Image)
        //                    {
        //                        var mc = new Image();
        //                        var Last = (elem as Image);
        //                        try
        //                        {
        //                            if (Last.Source is BitmapImage)
        //                            {
        //                                mc.Source = new BitmapImage(new Uri(((BitmapImage)(Last.Source)).UriSource.AbsolutePath));
        //                            }
        //                        }
        //                        catch { }
        //                        p.Inlines.Add(mc);
        //                    }
        //                    else if (elem is InlineRichTextBox)
        //                    {
        //                        //xamlString += XamlWriter.Save((InlineRichTextBox)elem);
        //                    }
        //                    else
        //                    {
        //                        p.Inlines.Add(elem);
        //                    }
        //                }
        //                else if (inline is Run)
        //                {
        //                    Run r = (inline as Run);
        //                    string rSer = XamlWriter.Save(r);
        //                    var inl1 = XamlReader.Parse(rSer);
        //                    p.Inlines.Add(inl1 as Run);
        //                }
        //                else if (inline is Span)
        //                {
        //                    Span r = (inline as Span);
        //                    string rSer = XamlWriter.Save(r);// NOT SERIALIZE properties "bold" and "color" and "size"
        //                    var inl1 = XamlReader.Parse(rSer);
        //                    p.Inlines.Add(inl1 as Span);
        //                }
        //                else
        //                {
        //                }
        //            }
        //            flowDocument.Blocks.Add(p);
        //        }
        //    }

        //    string aaa = XamlWriter.Save(flowDocument);

        //    var richtextbox = new RichTextEditor();
        //    richtextbox.Document.Blocks.Clear();

        //    object f = XamlReader.Parse(aaa);
        //    richtextbox.Document = f as FlowDocument;
        //    return aaa;
        //}


        //private string GetImagesXML(FlowDocument flowDocument)
        //{

        //    using (StringWriter stringwriter = new StringWriter())
        //    {
        //        using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(stringwriter))
        //        {

        //            Type inlineType;
        //            InlineUIContainer uic;
        //            System.Windows.Controls.Image replacementImage;
        //            byte[] bytes;
        //            System.Text.ASCIIEncoding enc;

        //            //loop through replacing images in the flowdoc with the byte versions
        //            foreach (Block b in flowDocument.Blocks)
        //            {
        //                foreach (Inline i in ((Paragraph)b).Inlines)
        //                {
        //                    inlineType = i.GetType();

        //                    if (inlineType == typeof(Run))
        //                    {
        //                        //The inline is TEXT!!!
        //                    }
        //                    else if (inlineType == typeof(InlineUIContainer))
        //                    {
        //                        //The inline has an object, likely an IMAGE!!!
        //                        uic = ((InlineUIContainer)i);

        //                        //if it is an image
        //                        if (uic.Child.GetType() == typeof(System.Windows.Controls.Image))
        //                        {
        //                            //grab the image
        //                            replacementImage = (System.Windows.Controls.Image)uic.Child;

        //                            //get its byte array
        //                            bytes = GetImageByteArray((BitmapImage)replacementImage.Source);
        //                            //write the element
        //                            writer.WriteStartElement("Image");
        //                            //put the bytes into the tag
        //                            enc = new System.Text.ASCIIEncoding();
        //                            writer.WriteString(enc.GetString(bytes));
        //                            //close the element
        //                            writer.WriteEndElement();
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        return stringwriter.ToString();
        //    }
        //}


        //This function is where the problem is, i need a way to get the byte array
        //private byte[] GetImageByteArray(BitmapImage bi)
        //{
        //    byte[] result = new byte[0];
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        XamlWriter.Save(bi, ms);
        //        //result = new byte[ms.Length];
        //        result = ms.ToArray();
        //    }
        //    return result;
        //}

        //private RichTextBox richTextBox;
        //private void SaveXML()
        //{
        //    var documentTextRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
        //    var flowDocument = richTextBox.Document;

        //    string s = GetImagesXML(flowDocument);//temp
        //    LoadImagesIntoXML(s);

        //    using (var stringwriter = new StringWriter())
        //    {
        //        using (var writer = System.Xml.XmlWriter.Create(stringwriter))
        //        {
        //            if (writer != null) XamlWriter.Save(flowDocument, writer);//Throws error here
        //        }

        //    }
        //}


        //private string GetImagesXML(FlowDocument flowDocument)
        //{
        //    string s = "";

        //    using (var stringwriter = new StringWriter())
        //    {
        //        InlineUIContainer uic;
        //        System.Windows.Controls.Image replacementImage;
        //        byte[] bytes;
        //        BitmapImage bi;

        //        //loop through replacing images in the flowdoc with the byte versions
        //        foreach (Block b in flowDocument.Blocks)
        //        {
        //            foreach (Inline i in ((Paragraph)b).Inlines)
        //            {
        //                var inlineType = i.GetType();

        //                if (inlineType == typeof(Run))
        //                {
        //                    //The inline is TEXT!!!
        //                }
        //                else if (inlineType == typeof(InlineUIContainer))
        //                {
        //                    //The inline has an object, likely an IMAGE!!!
        //                    uic = ((InlineUIContainer)i);

        //                    //if it is an image
        //                    if (uic.Child.GetType() == typeof(System.Windows.Controls.Image))
        //                    {
        //                        //grab the image
        //                        replacementImage = (System.Windows.Controls.Image)uic.Child;
        //                        bi = (BitmapImage)replacementImage.Source;

        //                        //get its byte array
        //                        bytes = GetImageByteArray(bi);

        //                        s = Convert.ToBase64String(bytes);//temp
        //                    }
        //                }
        //            }
        //        }

        //        return s;
        //    }
        //}

        //private byte[] GetImageByteArray(BitmapImage src)
        //{
        //    var stream = new MemoryStream();
        //    var encoder = new BmpBitmapEncoder();
        //    encoder.Frames.Add(BitmapFrame.Create((BitmapSource)src));
        //    encoder.Save(stream);
        //    stream.Flush();
        //    return stream.ToArray();
        //}


        //private void LoadImagesIntoXML(string xml)
        //{


        //    byte[] imageArr = Convert.FromBase64String(xml);
        //    var img = new System.Windows.Controls.Image();

        //    var stream = new MemoryStream(imageArr);
        //    var decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
        //    img.Source = decoder.Frames[0];
        //    img.Stretch = Stretch.None;

        //    var p = new Paragraph();
        //    p.Inlines.Add(img);
        //    richTextBox.Document.Blocks.Add(p);
        //}

        /// <summary>
        /// Returns a FlowDocument in SearchableText UI Binary (SUB)String format.
        /// </summary>
        /// <param name="flowDocument">The FlowDocument containing images/UI formats to be converted</param>
        /// <returns>Returns a string representation of the FlowDocument with images in base64 string in image tag property</returns>
        public static string ConvertFlowDocumentToSUBStringFormat(FlowDocument flowDocument)
        {
            //take the flow document and change all of its images into a base64 string
            //flowDocument.ClearValue(RichTextEditor.ContextMenuProperty);
            var temp = (FlowDocument)Utility.CloneElement(flowDocument);
            TransformImagesTo64(temp);

            //apply the XamlWriter to the newly transformed flowdocument
            //using (var stringwriter = new StringWriter())
            //{
            //    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(stringwriter))
            //    {
            //        XamlWriter.Save(flowDocument, writer);
            //    }
            //    return stringwriter.ToString();
            //}
            return XamlWriter.Save(temp);
        }
        /// <summary>
        /// Returns a FlowDocument with images in base64 stored in their own tag property
        /// </summary>
        /// <param name="flowDocument">The FlowDocument containing images/UI formats to be converted</param>
        /// <returns>Returns a FlowDocument with images in base 64 string in image tag property</returns>
        public static void TransformImagesTo64(FlowDocument flowDocument)
        {
            //loop through replacing images in the flowdoc with the base64 versions
            //foreach (Block b in flowDocument.Blocks)
            //{
            //    //loop through inlines looking for images
            //    if (b is Paragraph)
            //    {
            //        foreach (Inline i in ((Paragraph)b).Inlines)
            //        {
            //            var inlineType = i.GetType();

            //            /*if (inlineType == typeof(Run))
            //            {
            //                //The inline is TEXT!!! $$$$$ Kept in case needed $$$$$
            //            }
            //            else */
            //            if (inlineType == typeof(InlineUIContainer))
            //            {
            //                //The inline has an object, likely an IMAGE!!!
            //                var uic = ((InlineUIContainer)i);

            //                //if it is an image
            //                if (uic.Child.GetType() == typeof(System.Windows.Controls.Image))
            //                {
            //                    //grab the image
            //                    var replacementImage = (System.Windows.Controls.Image)uic.Child;

            //                    //create a new image to be used to get base64
            //                    var newImage = new System.Windows.Controls.Image();
            //                    //clone the image from the image in the flowdocument
            //                    newImage.Source = replacementImage.Source;

            //                    //create necessary objects to obtain a flowdocument in XamlFormat to get base 64 from
            //                    var img_inline = new InlineUIContainer(newImage);
            //                    var img_paragraph = new Paragraph(img_inline);
            //                    var img_flowDocument = new FlowDocument(img_paragraph);

            //                    //Get the base 64 version of the XamlFormat binary
            //                    replacementImage.Tag = TransformImageTo64String(img_flowDocument);
            //                    replacementImage.ClearValue(Image.SourceProperty);
            //                }
            //                else if (uic.Child.GetType() == typeof(InlineRichTextBox))
            //                {
            //                    foreach (var nb in ((InlineRichTextBox)uic.Child).Document.Blocks)
            //                    {
            //                        //loop through inlines looking for images
            //                        if (nb is Paragraph)
            //                        {
            //                            foreach (var ni in ((Paragraph)nb).Inlines)
            //                            {

            //                                if (ni is InlineUIContainer)
            //                                {
            //                                    //The inline has an object, likely an IMAGE!!!
            //                                    var nuic = ((InlineUIContainer)ni);

            //                                    //if it is an image
            //                                    if (nuic.Child is Image)
            //                                    {
            //                                        //grab the image
            //                                        var nreplacementImage = (Image)nuic.Child;

            //                                        //create a new image to be used to get base64
            //                                        var nnewImage = new System.Windows.Controls.Image();
            //                                        //clone the image from the image in the flowdocument
            //                                        nnewImage.Source = nreplacementImage.Source;

            //                                        //create necessary objects to obtain a flowdocument in XamlFormat to get base 64 from
            //                                        var nimg_inline = new InlineUIContainer(nnewImage);
            //                                        var nimg_paragraph = new Paragraph(nimg_inline);
            //                                        var nimg_flowDocument = new FlowDocument(nimg_paragraph);

            //                                        //Get the base 64 version of the XamlFormat binary
            //                                        nreplacementImage.Tag = TransformImageTo64String(nimg_flowDocument);
            //                                        nreplacementImage.ClearValue(Image.SourceProperty);

            //                                    }
            //                                }
            //                            }
            //                        }
            //                    }
            //                }
            //            }

            //        }
            //    }
            //    if(b is Table)
            //    {
            //        foreach (var tableRowGroup in ((Table)b).RowGroups)
            //        {
            //            foreach(var row in tableRowGroup.Rows)
            //            {
            //                foreach (var cell in row.Cells)
            //                {
            //                    foreach(var block in cell.Blocks)
            //                    {

            //                    }
            //                }
            //            }
            //        }
            //    }
            //}

            foreach (Block b in flowDocument.Blocks)
            {
                TransformImagesTo64(b);
            }

            //var xdoc = new XmlDocument();
            ////var teachingPlanNode = xdoc.CreateElement("Root");
            //////composingDateNode.InnerText = comDate;
            ////xdoc.AppendChild(teachingPlanNode);
            //var xfragPreparationNode = xdoc.CreateDocumentFragment();
            //xfragPreparationNode.InnerXml = (string)XamlWriter.Save(flowDocument);
            //xdoc.AppendChild(xfragPreparationNode);
            //var contextMenus = xdoc.GetElementsByTagName("ContextMenu");
            //for (int i = 0; i < contextMenus.Count; i++)
            //{
            //    var x = contextMenus[i];
            //    x.ParentNode.RemoveChild(x);
              
            //}

            //var temp = xdoc.GetElementsByTagName("Image");
            //for (int i = 0; i < temp.Count; i++)
            //{
            //    MessageBox.Show(temp[i].);
            //    MessageBox.Show(temp[i].InnerXml);
            //    MessageBox.Show(temp[i].InnerText);
            //    MessageBox.Show(temp[i].Value);
            //    try
            //    {
            //        var image = (Image)XamlReader.Load(new XmlTextReader(new StringReader(temp[i].InnerXml)));
            //        var img_inline = new InlineUIContainer(image);
            //        var img_paragraph = new Paragraph(img_inline);
            //        var img_flowDocument = new FlowDocument(img_paragraph);
            //        //Get the base 64 version of the XamlFormat binary
            //        MessageBox.Show(TransformImageTo64String(img_flowDocument));
            //        temp[i].Attributes["Source"].InnerXml = TransformImageTo64String(img_flowDocument);
            //    }
            //    catch (Exception e)
            //    {

            //    }
               
               
            //}


            //teachingPlanNode.AppendChild(preparationNode);
        }

        public static void TransformImagesTo64(Inline i)
        {
            var inlineType = i.GetType();

            if (inlineType == typeof(InlineUIContainer))
            {
                //The inline has an object, likely an IMAGE!!!
                var uic = ((InlineUIContainer)i);
                //if it is an image
                if (uic.Child.GetType() == typeof(System.Windows.Controls.Image))
                {
                    //grab the image
                    var replacementImage = (System.Windows.Controls.Image)uic.Child;
                    //create a new image to be used to get base64
                    var newImage = new System.Windows.Controls.Image();
                    //clone the image from the image in the flowdocument
                    newImage.Source = replacementImage.Source;
                    //create necessary objects to obtain a flowdocument in XamlFormat to get base 64 from
                    var img_inline = new InlineUIContainer(newImage);
                    var img_paragraph = new Paragraph(img_inline);
                    var img_flowDocument = new FlowDocument(img_paragraph);
                    //Get the base 64 version of the XamlFormat binary
                    replacementImage.Tag = TransformImageTo64String(img_flowDocument);
                    replacementImage.ClearValue(Image.SourceProperty);
                }
                else if (uic.Child.GetType() == typeof(InlineRichTextBox))
                {
                    var temp = (InlineRichTextBox)uic.Child;
                    temp.ClearValue(InlineRichTextBox.ContextMenuProperty);
                    foreach (var nb in temp.Document.Blocks)
                    {
                        TransformImagesTo64(nb);
                    }
                }
            }
            else if (inlineType == typeof(Span))
            {
                foreach (var spanInline in ((Span)i).Inlines)
                {
                    TransformImagesTo64(spanInline);
                }
            }
            else if (inlineType == typeof(AnchoredBlock))
            {
                foreach (var block in ((AnchoredBlock)i).Blocks)
                {
                    TransformImagesTo64(block);
                }
            }
        }

        public static void TransformImagesTo64(Block b)
        {
            if (b is Paragraph)
            {
                foreach (Inline i in ((Paragraph)b).Inlines)
                {
                    //var inlineType = i.GetType();
                    ///*if (inlineType == typeof(Run))
                    //{
                    //    //The inline is TEXT!!! $$$$$ Kept in case needed $$$$$
                    //}
                    //else */
                    //if (inlineType == typeof(InlineUIContainer))
                    //{
                    //    //The inline has an object, likely an IMAGE!!!
                    //    var uic = ((InlineUIContainer)i);
                    //    //if it is an image
                    //    if (uic.Child.GetType() == typeof(System.Windows.Controls.Image))
                    //    {
                    //        //grab the image
                    //        var replacementImage = (System.Windows.Controls.Image)uic.Child;
                    //        //create a new image to be used to get base64
                    //        var newImage = new System.Windows.Controls.Image();
                    //        //clone the image from the image in the flowdocument
                    //        newImage.Source = replacementImage.Source;
                    //        //create necessary objects to obtain a flowdocument in XamlFormat to get base 64 from
                    //        var img_inline = new InlineUIContainer(newImage);
                    //        var img_paragraph = new Paragraph(img_inline);
                    //        var img_flowDocument = new FlowDocument(img_paragraph);
                    //        //Get the base 64 version of the XamlFormat binary
                    //        replacementImage.Tag = TransformImageTo64String(img_flowDocument);
                    //        replacementImage.ClearValue(Image.SourceProperty);
                    //    }
                    //    else if (uic.Child.GetType() == typeof(InlineRichTextBox))
                    //    {
                    //        var temp = (InlineRichTextBox)uic.Child;
                    //        temp.ClearValue(InlineRichTextBox.ContextMenuProperty);
                    //        foreach (var nb in temp.Document.Blocks)
                    //        {
                    //            TransformImagesTo64(nb);
                    //        }
                    //    }
                    //}
                    //else if (inlineType == typeof(Span))
                    //{
                    //    foreach (var spanInline in ((Span)i).Inlines)
                    //    {
                    //        //The inline has an object, likely an IMAGE!!!
                    //        if (spanInline is InlineUIContainer)
                    //        {
                    //            var uic = ((InlineUIContainer)spanInline);

                    //            //if it is an image
                    //            //if (uic.Child.GetType() == typeof(System.Windows.Controls.Image))
                    //            //{
                    //            //    //grab the image
                    //            //    var replacementImage = (System.Windows.Controls.Image)uic.Child;
                    //            //    //create a new image to be used to get base64
                    //            //    var newImage = new System.Windows.Controls.Image();
                    //            //    //clone the image from the image in the flowdocument
                    //            //    newImage.Source = replacementImage.Source;
                    //            //    //create necessary objects to obtain a flowdocument in XamlFormat to get base 64 from
                    //            //    var img_inline = new InlineUIContainer(newImage);
                    //            //    var img_paragraph = new Paragraph(img_inline);
                    //            //    var img_flowDocument = new FlowDocument(img_paragraph);
                    //            //    //Get the base 64 version of the XamlFormat binary
                    //            //    replacementImage.Tag = TransformImageTo64String(img_flowDocument);
                    //            //    replacementImage.ClearValue(Image.SourceProperty);
                    //            //}
                    //            //else 
                    //            if (uic.Child.GetType() == typeof(InlineRichTextBox))
                    //            {
                    //                var temp = (InlineRichTextBox)uic.Child;
                    //                temp.ClearValue(InlineRichTextBox.ContextMenuProperty);
                    //                foreach (var nb in temp.Document.Blocks)
                    //                {
                    //                    TransformImagesTo64(nb);
                    //                }
                    //            }
                    //        }
                    //    }
                    //} else if (inlineType == typeof(AnchoredBlock))
                    //{
                    //    foreach (var block in ((AnchoredBlock)i).Blocks)
                    //    {
                    //        TransformImagesTo64(block);
                    //    }
                    //}
                    TransformImagesTo64(i);
                }
            }
            else if (b is Table)
            {
                foreach (var tableRowGroup in ((Table)b).RowGroups)
                {
                    foreach (var row in tableRowGroup.Rows)
                    {
                        foreach (var cell in row.Cells)
                        {
                            foreach (var block in cell.Blocks)
                            {
                                TransformImagesTo64(block);
                            }
                        }
                    }
                }
            }
            else if (b is List)
            {
                foreach (var listItem in ((List)b).ListItems)
                {
                    foreach (var block in listItem.Blocks)
                    {
                        TransformImagesTo64(block);
                    }
                }
            }
            else if (b is Section)
            {
                foreach (var block in ((Section)b).Blocks)
                {
                    TransformImagesTo64(block);
                }
            }
            else if (b is BlockUIContainer)
            {
                foreach (var rtb in Utility.FindVisualChildren<RichTextEditor>(((BlockUIContainer)b).Child))
                {
                    foreach (var block in rtb.Document.Blocks)
                    {
                        TransformImagesTo64(block);
                    }
                }
            }

        }


        public static FlowDocument Transform64ToImage(FlowDocument flowDocument)
        {
            //var flowDoc = new FlowDocument();
            //InlineUIContainer inlineUiContainer;
            //System.Windows.Controls.Image replacementImage;

            //loop through replacing images in the flowdoc with the base64 versions
            foreach (var block in flowDocument.Blocks)
            {
                //loop through inlines looking for images
                Transform64ToImage(block);
            }
            //flowDocument = flowDoc;
            return flowDocument;
        }
        public static void Transform64ToImage(Inline inline)
         {
             if (inline is InlineUIContainer)
             {
                 //The inline has an object, likely an IMAGE!!!
                 var inlineUiContainer = ((InlineUIContainer)inline);

                 //if it is an image
                 if (inlineUiContainer.Child is System.Windows.Controls.Image)
                 {
                     //grab the image
                     var replacementImage = (System.Windows.Controls.Image)inlineUiContainer.Child;

                     var flowDoc = LoadXAMLPackage(Base64ToBytes(replacementImage.Tag.ToString()));
                     foreach (var nb in flowDoc.Blocks)
                     {
                         //loop through inlines looking for images
                         foreach (var ni in ((Paragraph)nb).Inlines)
                         {

                             if (ni is InlineUIContainer)
                             {
                                 //The inline has an object, likely an IMAGE!!!
                                 var nuic = ((InlineUIContainer)ni);
                                 //if it is an image
                                 if (nuic.Child is Image)
                                 {
                                     //grab the image
                                     replacementImage.Source =
                                         (ImageSource)(Utility.CloneElement(((Image)nuic.Child).Source));
                                     replacementImage.Loaded += delegate
                                     {
                                         AdornerLayer al = AdornerLayer.GetAdornerLayer(replacementImage);
                                         if (al != null)
                                         {
                                             al.Add(new ResizingAdorner(replacementImage));
                                         }
                                     };
                                 }
                             }
                         }
                     }
                 }
                 if (inlineUiContainer.Child is InlineRichTextBox)
                 {
                     //grab the image
                     var inlineRichTextBox = (InlineRichTextBox)inlineUiContainer.Child;
                     foreach (var nblock in inlineRichTextBox.Document.Blocks)
                     {
                         Transform64ToImage(nblock);
                     }
                 }
             }
             else if (inline is Span)
             {
                 foreach (var spanInline in ((Span)inline).Inlines)
                 {
                     if (spanInline is InlineUIContainer)
                     {
                         Transform64ToImage(spanInline);
                     }
                 }
             }
             else if (inline is AnchoredBlock)
             {
                 foreach (var nblock in ((AnchoredBlock)inline).Blocks)
                 {
                     Transform64ToImage(nblock);
                 }
             }
         }
        public static void Transform64ToImage(Block block)
        {

            //loop through inlines looking for images
            if (block is Paragraph)
            {
                foreach (var inline in ((Paragraph)block).Inlines)
                {
                    Transform64ToImage(inline);
                    //if (inline is InlineUIContainer)
                    //{
                    //    //The inline has an object, likely an IMAGE!!!
                    //    var inlineUiContainer = ((InlineUIContainer)inline);

                    //    //if it is an image
                    //    if (inlineUiContainer.Child is System.Windows.Controls.Image)
                    //    {
                    //        //grab the image
                    //        var replacementImage = (System.Windows.Controls.Image)inlineUiContainer.Child;

                    //        var flowDoc = LoadXAMLPackage(Base64ToBytes(replacementImage.Tag.ToString()));
                    //        foreach (var nb in flowDoc.Blocks)
                    //        {
                    //            //loop through inlines looking for images
                    //            foreach (var ni in ((Paragraph)nb).Inlines)
                    //            {

                    //                if (ni is InlineUIContainer)
                    //                {
                    //                    //The inline has an object, likely an IMAGE!!!
                    //                    var nuic = ((InlineUIContainer)ni);
                    //                    //if it is an image
                    //                    if (nuic.Child is Image)
                    //                    {
                    //                        //grab the image
                    //                        replacementImage.Source =
                    //                            (ImageSource)(Utility.CloneElement(((Image)nuic.Child).Source));
                    //                    }
                    //                }
                    //            }
                    //        }
                    //    }
                    //    if (inlineUiContainer.Child is InlineRichTextBox)
                    //    {
                    //        //grab the image
                    //        var inlineRichTextBox = (InlineRichTextBox)inlineUiContainer.Child;
                    //        foreach (var nblock in inlineRichTextBox.Document.Blocks)
                    //        {
                    //            Transform64ToImage(nblock);
                    //        }
                    //    }
                    //}
                    //else if (inline is Span)
                    //{
                    //    foreach (var spanInline in ((Span)inline).Inlines)
                    //    {
                    //        if (spanInline is InlineUIContainer)
                    //        {
                    //            if (((InlineUIContainer)spanInline).Child is InlineRichTextBox)
                    //            {
                    //                //grab the image
                    //                var inlineRichTextBox = (InlineRichTextBox)((InlineUIContainer)spanInline).Child;
                    //                foreach (var nblock in inlineRichTextBox.Document.Blocks)
                    //                {
                    //                    Transform64ToImage(nblock);
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    //else if (inline is AnchoredBlock)
                    //{
                    //    foreach (var nblock in ((AnchoredBlock)inline).Blocks)
                    //    {
                    //        Transform64ToImage(nblock);
                    //    }
                    //}
                }
            }
            else if (block is Table)
            {
                foreach (var tableRowGroup in ((Table)block).RowGroups)
                {
                    foreach (var row in tableRowGroup.Rows)
                    {
                        foreach (var cell in row.Cells)
                        {
                            foreach (var nblock in cell.Blocks)
                            {
                                Transform64ToImage(nblock);
                            }
                        }
                    }
                }
            }
            else if (block is List)
            {
                foreach (var listItem in ((List)block).ListItems)
                {
                    foreach (var nblock in listItem.Blocks)
                    {
                        Transform64ToImage(nblock);
                    }
                }
            }
            else if (block is Section)
            {
                foreach (var nblock in ((Section)block).Blocks)
                {
                    Transform64ToImage(nblock);
                }
            }
            else if (block is BlockUIContainer)
            {
                foreach (var rtb in Utility.FindVisualChildren<RichTextEditor>(((BlockUIContainer)block).Child))
                {
                    foreach (var nblock in rtb.Document.Blocks)
                    {
                        Transform64ToImage(nblock);
                    }
                }
            }
        }
        /// <summary>
        /// Takes a FlowDocument containing a SINGLE Image, and converts to base 64 using XamlFormat
        /// </summary>
        /// <param name="flowDocument">The FlowDocument containing a SINGLE Image</param>
        /// <returns>Returns base 64 representation of image</returns>
        public static string TransformImageTo64String(FlowDocument flowDocument)
        {
            return BytesToBase64(ToByteArray(flowDocument));
        }

        //****
        public static byte[] ToByteArray(FlowDocument flowDocument)
        {
            // Returns RichTextBox content as a byte array to allow to saving to database as varbinary
            if (flowDocument.Blocks.Count == 0)
            {
                return null;
            }

            var memoryStream = new MemoryStream();
            var textRange = new System.Windows.Documents.TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
            textRange.Save(memoryStream, DataFormats.XamlPackage);
            byte[] byteArray = new byte[memoryStream.Length];
            byteArray = memoryStream.ToArray();
            memoryStream.Close();

            return byteArray;
        }

        public static string BytesToBase64(byte[] byteData)
        {
            return Convert.ToBase64String(byteData,
                Base64FormattingOptions.InsertLineBreaks);
        }
        public static byte[] Base64ToBytes(string sText_Base64)
        {
            return Convert.FromBase64String(sText_Base64);
        }
        public static FlowDocument LoadXAMLPackage(byte[] arrayByte)
        {
            // Loads RichTextBox content from byte array
            try
            {
                var memoryStream = new MemoryStream(arrayByte);
                //memoryStream.Read(arrayByte, 0, arrayByte.Length);

                var flowDocument = new FlowDocument();
                var textRange = new System.Windows.Documents.TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
                textRange.Load(memoryStream, DataFormats.XamlPackage);
                return flowDocument;
            }
            catch (Exception ex)
            {
                //throw;
                // log.Info("Program Started " + DateTime.Now.ToString());
            }
            return null;
        }
    }
}
